package com.hpin.mlxteacher.fragment;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hpin.mlxteacher.R;
import com.hpin.mlxteacher.base.BaseFragment;
import com.hpin.mlxteacher.mqttsource.MqttException;
import com.hpin.mlxteacher.my.AboutActivity;
import com.hpin.mlxteacher.my.AddressBookActivity;
import com.hpin.mlxteacher.my.SettingActivity;
import com.hpin.mlxteacher.ui.LoginActivity;
import com.hpin.mlxteacher.utils.CommonUtils;
import com.hpin.mlxteacher.utils.Constant;
import com.hpin.mlxteacher.widget.CircleImageView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;
import com.umeng.update.UmengUpdateAgent;
import com.umeng.update.UmengUpdateListener;
import com.umeng.update.UpdateResponse;
import com.umeng.update.UpdateStatus;

import java.util.LinkedHashSet;
import java.util.Random;
import java.util.Set;

//import com.umeng.analytics.MobclickAgent;

/**
 * 我的fragment
 * Created by Aaron on 2015/7/15.
 */
public class MyFragement extends BaseFragment implements View.OnClickListener {

    private CircleImageView cv_headpic;
    private Intent mIntent;
    private TextView tv_name;
    private RelativeLayout rl_random;
    public DisplayImageOptions options;
    private int[] bgPics = {R.drawable.my_bg_1, R.drawable.my_bg_2, R.drawable.my_bg_3, R.drawable.my_bg_4
            , R.drawable.my_bg_5, R.drawable.my_bg_6, R.drawable.my_bg_7, R.drawable.my_bg_8};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View myView = inflater.inflate(R.layout.fragment_my, null);

        initWidget(myView);

        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.icon_person)
                .showImageForEmptyUri(R.drawable.icon_person)
                .showImageOnFail(R.drawable.icon_person)
                .resetViewBeforeLoading(true)
                .cacheOnDisk(true).cacheInMemory(true)
                .cacheOnDisc(true).imageScaleType(ImageScaleType.EXACTLY)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .considerExifParams(true)
                .displayer(new SimpleBitmapDisplayer()).build();
        rl_random.setBackgroundResource(bgPics[new Random().nextInt(8)]);

        return myView;
    }

    @Override
    public void onResume() {
        super.onResume();

        //昵称
        tv_name.setText(sp.getString(Constant.nickName, ""));
        //头像
        ImageLoader.getInstance().displayImage(sp.getString(Constant.imgUrl, ""), cv_headpic, options);

//        LogUtil.e("tag", "fragment 头像:" + sp.getString(Constant.imgUrl, ""));
//        MobclickAgent.onPageStart(getClass().getName()); //统

        // 计页面
    }

    public void onPause() {
        super.onPause();
//        MobclickAgent.onPageEnd(getClass().getName());
    }

    private void initWidget(View myView) {

        TextView tv_title = (TextView) myView.findViewById(R.id.tv_title);

        tv_title.setText(getResources().getString(R.string.rl_my));

        cv_headpic = (CircleImageView) myView.findViewById(R.id.cv_headpic);//头像
        rl_random = (RelativeLayout) myView.findViewById(R.id.rl_random);//头像

        tv_name = (TextView) myView.findViewById(R.id.tv_name);
        TextView tv_version_name = (TextView) myView.findViewById(R.id.tv_version_code);//版本号
        TextView tv_quit = (TextView) myView.findViewById(R.id.tv_quit);//退出

        RelativeLayout rl_personal_setting = (RelativeLayout) myView.findViewById(R.id.rl_personal_setting);//个人设置
        RelativeLayout rl_address_book = (RelativeLayout) myView.findViewById(R.id.rl_address_book);//通讯录
        RelativeLayout rl_about = (RelativeLayout) myView.findViewById(R.id.rl_about);//关于
        RelativeLayout rl_version_code = (RelativeLayout) myView.findViewById(R.id.rl_version_code);//版本号

        rl_personal_setting.setOnClickListener(this);
        rl_address_book.setOnClickListener(this);
        rl_about.setOnClickListener(this);
        rl_version_code.setOnClickListener(this);
        tv_quit.setOnClickListener(this);

        //版本号
        String versionName = getPackageInfo(getActivity()).versionName;
        tv_version_name.setText(versionName);

    }

    public PackageInfo getPackageInfo(Context context) {
        PackageInfo pi = null;

        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_CONFIGURATIONS);

            return pi;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return pi;
    }


    @Override
    public void onClick(View view) {

        switch (view.getId()) {

            case R.id.rl_personal_setting://个人设置

                mIntent = new Intent(getActivity(), SettingActivity.class);
                startActivity(mIntent);

                break;
            case R.id.rl_address_book://通讯录

                mIntent = new Intent(getActivity(), AddressBookActivity.class);
                startActivity(mIntent);
                break;
            case R.id.rl_about://关于

                mIntent = new Intent(getActivity(), AboutActivity.class);
                startActivity(mIntent);
                break;
            case R.id.rl_version_code://版本号

                UmengUpdateAgent.forceUpdate(getActivity());
                UmengUpdateAgent.setUpdateListener(new UmengUpdateListener() {
                    @Override
                    public void onUpdateReturned(int updateStatus, UpdateResponse updateInfo) {
                        switch (updateStatus) {
                            case UpdateStatus.Yes: // has update
                                UmengUpdateAgent.showUpdateDialog(getActivity(), updateInfo);
                                break;
                            case UpdateStatus.No: // has no update
                                Toast.makeText(getActivity(), "没有更新", Toast.LENGTH_SHORT).show();
                                break;
                            case UpdateStatus.NoneWifi: // none wifi
                                Toast.makeText(getActivity(), "没有wifi连接， 只在wifi下更新", Toast.LENGTH_SHORT).show();
                                break;
                            case UpdateStatus.Timeout: // time out
                                Toast.makeText(getActivity(), "超时", Toast.LENGTH_SHORT).show();
                                break;
                        }
                    }
                });
                break;
            case R.id.tv_quit://退出

                quit();

                break;

        }

    }

    //退出
    private void quit() {

        new AlertDialog.Builder(getActivity()).setTitle("提示").setMessage("确定要退出吗?").setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                Set<String> remaindSet = sp.getStringSet(Constant.REMAIND + sp.getString(Constant.phoneNum, ""), new LinkedHashSet<String>());
                String userId = sp.getString(Constant.phoneNum, "");

                //删除用户的数据信息
                sp.edit().clear().apply();
                //保存 消息不提醒的topic至文件中
                CommonUtils.fileSave(Constant.REMAIND + userId, remaindSet);

                dialog.dismiss();
                try {

                    //退出mqtt
                    mApplication.exitMqtt();

                } catch (MqttException e) {
                    e.printStackTrace();
                    showToast("退出失败");
                }

                //回到登录页面
                mIntent = new Intent(getActivity(), LoginActivity.class);
                startActivity(mIntent);

            }
        }).show();

    }
}
